<script lang="ts" setup>
import { computed, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import {Button, message, Space} from 'ant-design-vue'

import { useVbenForm } from '#/adapter/form'
import {dictAdd, dictInfo, dictUpdata} from '#/api/dict'

const emit = defineEmits(['refresh'])
const idsArr: any = ref([])
const inputDisabled = ref(true)
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  layout: 'horizontal',
  schema: [
    { component: 'Input', fieldName: 'dict_name', label: '名称',rules:'required' },
    {
      component: 'Input',
      fieldName: 'dict_key',
      label: '字典KEY',
      rules:'required',
      componentProps: {
        disabled: inputDisabled,
      },
    },
  ],
  wrapperClass: 'grid-cols-1',
})

const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[30%] h-[30%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()
      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        if (Array.isArray(rowData)) {
          // 如果是多个编辑
          idsArr.value = rowData
          initData(rowData[0])
        } else {
          inputDisabled.value = true
          initData(rowData)
        }
      }
    }
  },
})

async function initData(rowData: any) {
  dictInfo({ dict_id: rowData }).then(async (response) => {
    const row = response.row
    await baseFormApi.setValues(row, false)
  })
}
const Text: any = computed(() => {
  return idsArr.value.length > 1 ? '保存并编辑下一项' : '保存'
})

// 保存
async function save() {
  const { valid } = await baseFormApi.validate()
  if (!valid) {
    return
  }
  const values = await baseFormApi.getValues()
  console.log(values)
  const parmas = {
    ...values,
  }
  if (values.dict_id) {
    // 如果是多个编辑
    if (idsArr.value.length > 1) {
      dictUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          const index = idsArr.value.indexOf(values.dict_id)
          // 如果找到了对应的值，使用 splice 删除它
          if (index !== -1) {
            idsArr.value.splice(index, 1)
            initData(idsArr.value[0])
          }
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      dictUpdata(parmas).then((res: any) => {
        if (res.data.code === 1) {
          message.success(res.data.msg)
          modalApi.close()
          emit('refresh')
        } else {
          message.error(res.data.msg)
        }
      })
    }
  } else {
    dictAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }
}

</script>
<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm />
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button type="primary" @click="save()">{{ Text }}</Button>
        </Space>
      </div>
    </template>
  </Modal>
</template>

<style scoped></style>
